package com.example.api;

import com.example.api.dto.ExecuteUserDTO;
import com.example.api.dto.TiggerDTO;
import com.fasterxml.jackson.databind.json.JsonMapper;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

/**
 * @author fanhang
 */
public class JobApiClient implements JobApi {
    private final HttpClient client = HttpClient.newBuilder().followRedirects(HttpClient.Redirect.NEVER).build();
    private final String endpoint;
    private final JsonMapper jsonMapper;

    public JobApiClient(String endpoint, JsonMapper jsonMapper) {
        this.endpoint = endpoint;
        this.jsonMapper = jsonMapper;
    }

    @Override
    public boolean executeUser(ExecuteUserDTO user) {
        try {
            byte[] result = this.execute(EXECUTE_USER, user);
            return jsonMapper.readValue(result, Boolean.class);
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String tigger(TiggerDTO tigger) {
        try {
            byte[] result = this.execute(TIGGER, tigger);
            return jsonMapper.readValue(result, String.class);
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    private byte[] execute(String uri, Object body) throws IOException, InterruptedException {
        URI requestUri = URI.create(this.endpoint + uri);
        HttpRequest.BodyPublisher bodyPublisher = HttpRequest.BodyPublishers.ofByteArray(jsonMapper.writeValueAsBytes(body));
        HttpRequest request = HttpRequest.newBuilder().uri(requestUri).POST(bodyPublisher).build();
        HttpResponse<byte[]> response = this.client.send(request, HttpResponse.BodyHandlers.ofByteArray());
        if (response.statusCode() != 200) {
            throw new RuntimeException("http execute error");
        }
        return response.body();
    }
}
